package pe.com.itworth.ttsclient.infrastructure;

import java.util.ArrayList;
import java.util.Collection;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class ParserGSON implements Parser<Object> {

	private GsonBuilder gsonb = new GsonBuilder();
	private Gson gson = gsonb.create();

	public String aCadena(Object objeto) {
		return gson.toJson(objeto);
	}

	public Object aObjeto(String cadena, Class clase) {
		try {
			JSONObject j = new JSONObject(cadena);
			return gson.fromJson(j.toString(), clase);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public Collection<Object> aArreglo(String cadena, Class clase) {
		Collection<Object> objetos = new ArrayList<Object>();
		try {
			JSONArray j = new JSONArray(cadena);
			for(int i = 0; i < j.length(); i++) {
				String json = j.getString(i);
				objetos.add(aObjeto(json, clase));
			}
			return objetos;
				
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	public boolean aBooleano(String respuesta) {
		return gson.fromJson(respuesta, Boolean.class);
	}

}
